﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Cost.Models;
using NBlock.Core.ORM;
using System.Web.Security;

namespace Cost.Services
{
    public class UserService
    {
        #region 构造函数
        public readonly ICostRepository<UserInfo> userRepo;
        public readonly ICostRepository<Organization> orgRepo;

        public UserService(ICostRepository<UserInfo> userRepo,
            ICostRepository<Organization> orgRepo)
        {
            this.userRepo = userRepo;
            this.orgRepo = orgRepo;

        }
        #endregion

        public UserInfo GetUserInfo(string Id, string orgId)
        {
            var user = userRepo.Find(Id);
            if (user == null)
            {
                // 设置初始化值
                user = new UserInfo();
                user.AccountStateEnum = AccountState.Normal;
                user.SeqNo = 9999;

                var org = orgRepo.Find(orgId);
                if (org != null)
                {
                    user.OrgId = org.Id;
                    user.OrgName = org.OrgName;
                    user.OrgCode = org.OrgCode;
                }
            }
            return user;
        }

        /// <summary>
        /// 获取指定部门Id下的所有用户（包含子部门的用户）
        /// </summary>
        /// <param name="orgId">部门Id</param>
        /// <returns></returns>
        public IList<UserInfo> GetUsersByFullOrgId(string orgId)
        {
            var users = new List<UserInfo>();
            if (string.IsNullOrEmpty(orgId))
            {
                users = userRepo.FindAll(u => u.OrgId != "").OrderBy(u => u.SeqNo).ToList();
            }
            else
            {
                var orgIds = orgRepo.FindAll(o => o.FullPath.Contains(orgId)).Select(o => o.Id).ToArray();
                users = userRepo.FindAll(u => orgIds.Contains(u.OrgId)).OrderBy(u => u.SeqNo).ToList();
            }
            return users;
        }

        public void SaveUser(UserInfo data)
        {
            data.OrgCode = data.OrgCode ?? string.Empty;
            data.OrgId = data.OrgId ?? string.Empty;
            data.OrgName = data.OrgName ?? string.Empty;
            if (!string.IsNullOrWhiteSpace(data.Password) && string.IsNullOrEmpty(data.CreateUserId))
            {
                data.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(data.Password, "md5");
            }
            userRepo.Save(data);
        }

        public bool IsValidCode(string Id, string UserCode)
        {
            return !userRepo.IsExist(p => p.UserCode == UserCode && p.Id != Id);
        }
    }
}